<template>
  <!--  质检记录-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline" label-width="auto" style="width: 100%">
        <el-row>
          <el-col :span="6">
            <el-form-item label="单号">
              <el-input v-model="searchParam.no" placeholder="请输入单号" clearable style="width: 265px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="来源单号">
              <el-input v-model="searchParam.sourceNo" placeholder="请输入来源单号" clearable style="width: 265px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质检类型">
              <el-select v-model="searchParam.qualityType" placeholder="请选择质检类型" clearable style="width: 265px">
                <el-option v-for="(item, index) of qualityTypeList" :key="index" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批次号">
              <el-input v-model="searchParam.batchNo" placeholder="请输入批次号" clearable style="width: 265px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 可展开的检索条件 -->
        <el-collapse-transition>
          <el-row v-if="expandSearch">
            <el-col :span="6">
              <el-form-item label="物料编码">
                <el-input v-model="searchParam.materialNo" placeholder="请输入物料编码" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="工序名称">
                <el-input v-model="searchParam.procedureName" placeholder="请输入工序名称" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="机台">
                <el-input v-model="searchParam.deviceCode" placeholder="请输入机台编码" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="总体数量">
                <el-input v-model="searchParam.batchTotalQuantity" placeholder="请输入总体数量" clearable
                          style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="质检方案名称">
                <el-input v-model="searchParam.name" placeholder="请输入质检方案名称" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="有效状态">
                <el-select v-model="searchParam.effectiveStatus" placeholder="请选择有效状态" clearable style="width: 265px">
                  <el-option label="无效" :value="0"/>
                  <el-option label="有效" :value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="抽检数量">
                <el-input v-model="searchParam.totalQuantity" placeholder="请输入抽检数量" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品状态">
                <el-select v-model="searchParam.materialStatus" placeholder="请选择有效状态" clearable style="width: 265px">
                  <el-option v-for="(item,index) of materialStatusList" :key="index" :label="item" :value="item"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委外电镀码">
                <el-input v-model="searchParam.platingCode" placeholder="请输入委外电镀码" clearable style="width: 265px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间">
                <el-date-picker
                    v-model="searchParam.createTimeList"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 625px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="特殊放行">
                <el-select v-model="searchParam.isCheck" placeholder="请选择特殊放行" clearable style="width: 265px">
                  <el-option label="是" :value="0"/>
                  <el-option label="否" :value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-transition>

        <!-- 按钮放在最下面，单行且靠右 -->
        <el-row justify="end" style="wid">
          <el-col :span="24" style="text-align: right;">
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch()">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
              <el-button type="text" @click="expandSearch = !expandSearch">
                {{ expandSearch ? '收起' : '展开' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <!--        <div class="pageTableButView">-->
        <!--          <el-button :icon="Plus" @click="handleAdd()">新建</el-button>-->
        <!--        </div>-->
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border :height="tableHeight">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize
              + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="no" label="单号" align="center" min-width="200"/>
        <el-table-column prop="materialNo" label="物料" align="center" min-width="200"/>
        <el-table-column prop="deviceCode" label="机台" align="center" min-width="160"/>
        <el-table-column prop="procedureName" label="工序" align="center" min-width="160"/>
        <el-table-column prop="batchTotalQuantity" label="总体数量" align="center" min-width="110"/>
        <el-table-column prop="nextCreateTime" label="下次巡检时间" align="center" min-width="200"/>
        <el-table-column prop="qualityType" label="质检类型" align="center" min-width="200">
          <template #default="scope">
            <span> {{ getQualityTypeByValue(scope.row.qualityType) }} </span></template>
        </el-table-column>
        <el-table-column prop="sourceNo" label="来源单号" align="center" min-width="200"/>
        <el-table-column prop="passRate" label="合格率" align="center" min-width="100">
          <template #default="scope">
            <div v-if="scope.row.passRate"> {{ scope.row.passRate }} %</div>
          </template>
        </el-table-column>
        <el-table-column prop="qualityPlan" label="质检方案" align="center" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            {{ JSON.parse(scope.row.qualityJson).name }}
          </template>
        </el-table-column>
        <el-table-column prop="qualityPlan" label="质检方式" align="center" min-width="110">
          <template #default="scope">
            {{ getQualityWay(JSON.parse(scope.row.qualityJson).qualityWay) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalQuantity" label="抽检数量" align="center" min-width="110"/>
        <el-table-column prop="schemeTaskForm.qualifiedQuantity" label="合格数" align="center" min-width="100"/>
        <el-table-column prop="schemeTaskForm.unQualifiedQuantity" label="不合格数" align="center"
                         min-width="100"/>
        <el-table-column prop="invalidReason" label="取消原因" align="center" min-width="200"/>
        <el-table-column prop="remark" label="备注" align="center" min-width="200"/>
        <el-table-column prop="updateUserName" label="更新人" align="center" min-width="120"/>
        <el-table-column prop="batchNo" label="批次号" align="center" min-width="200"/>
        <el-table-column prop="createTime" label="创建时间" align="center" min-width="200"/>
        <el-table-column prop="updateTime" label="更新时间" align="center" min-width="200"/>
        <!--        <el-table-column prop="statusShow" label="质检" align="center" min-width="200">-->
        <!--          <template #default="scope">-->
        <!--            <div v-if="scope.row.statusShow">已完结</div>-->
        <!--            <div v-else>未完结</div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template #default="scope">
            <el-button @click="handleConfigEdit(scope.row)" size="small" type="text" icon="Edit"> 详情
            </el-button>
            <el-button @click="handleExport(scope.row)" size="small" type="text" icon="Download"> 导出质检项
            </el-button>
            <!--            <el-button @click="handleConfigEdit(scope.row)" :disabled="scope.row.statusShow" type="warning" size="small"-->
            <!--                       plain :icon="DocumentCopy">结果录入-->
            <!--            </el-button>-->
            <!--            <el-button @click="handleDel(scope.row)" :disabled="scope.row.statusShow" type="danger" size="small" plain-->
            <!--                       :icon="Delete">删除-->
            <!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current"
                       v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100]"
                       layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <el-dialog v-model="configTableShow" title="质检详情" width="95%" top="5vh">
      <el-form :model="formData" label-width="100px" ref="ruleFormRef" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="来源单号："> {{ formData.sourceNo }}</el-form-item>
          </el-col>
          <!-- <el-col :span="6">
  <el-form-item label="检验方式：">
    {{ formData.samplingMethod }}
  </el-form-item>
</el-col> -->
          <el-col :span="6">
            <el-form-item label="质检方案："> {{ getQualityPlan(formData.qualityPlan) }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质检方式："> {{ getQualityWay(formData.qualityWay) }}</el-form-item>
          </el-col>
          <el-col :span="6" v-if="formData.qualityWay == 2">
            <el-form-item label="比例抽检："> {{ formData.proportionNumber }}%</el-form-item>
          </el-col>
          <el-col :span="6" v-if="formData.qualityWay == 3">
            <el-form-item label="固定抽检："> {{ formData.qualityNumber }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质检类型：" prop="qualityType"> {{ getQualityTypeList(formData.qualityType) }}
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="formData.qualityType == 4">
            <el-form-item label="巡检间隔：" prop="qualityInterval"> {{ formData.qualityInterval }} 小时
              <!--              <el-input-number v-model="formData.qualityInterval" :step="1" step-strictly :min="0" disabled/>-->
              <!--              （小时）-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方案说明：" prop="qualityRemark"> {{ formData.qualityRemark || '--' }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form :model="schemeTaskForm" label-width="100px" class="demo-ruleForm">
        <el-row :gutter="10">
          <!-- 检验标准录入方式 -->
          <el-col :span="6">
            <el-form-item label="合格数量："> {{ schemeTaskForm.qualifiedQuantity }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="不合格数量："> {{ schemeTaskForm.unQualifiedQuantity }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="不良原因："> {{ schemeTaskForm.schemeTaskRemark || '--' }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="configTable" height="calc(100vh - 500px)" border style="width: 100%">
        <el-table-column fixed="left" label="序号" type="index" align="center" width="60"></el-table-column>
        <el-table-column prop="workpieceNumber" fixed="left" align="center" label="抽样编号" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="testitemName" align="center" label="质检项名称" min-width="180" fixed="left"
                         show-overflow-tooltip/>
        <el-table-column prop="judgmentCriteria" align="center" label="检验标准录入方式" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="upperValue" align="center" label="上公差" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="defaultValue" align="center" label="默认值" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="lowerValue" align="center" label="下公差" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="defectMethod" align="center" label="不良判定方式" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="otherDefect" align="center" label="标准值" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="memo" align="center" label="备注" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="isEnable" align="center" label="是否启用" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="upperBias" align="center" label="上警戒值" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="lowerBias" align="center" label="下警戒值" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="excelCoordinate" align="center" label="SPC坐标" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="fullSizeCoordinate" align="center" label="全尺寸坐标" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="toolCoordinate" align="center" label="量具坐标" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="spcInspection" align="center" label="SPC检" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="fullSizeInspection" align="center" label="全尺寸检" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="failNameCode" align="center" label="文件名称" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="testitemCode" align="center" label="质检项代码" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="testitemclassificationName" align="center" label="质检类型" min-width="180"
                         show-overflow-tooltip/>
        <el-table-column prop="dataType" align="center" label="数值类型" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="realityNumber" align="center" label="实际测量值" min-width="130" fixed="right"
                         show-overflow-tooltip>
          <!--          <template #default="scope">-->
          <!--            <el-input v-model="scope.row.realityNumber" disabled placeholder="实际测量值" type="number"-->
          <!--                      style="width: 120px"/>-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column prop="dataType" align="center" label="是否合格" min-width="150" fixed="right"
                         show-overflow-tooltip>
          <template #default="scope">
            <div v-if="scope.row.isQualified">合格</div>
            <div v-else>不合格</div>
          </template>
        </el-table-column>
        <el-table-column prop="qualifiedMark" align="center" label="不良原因" fixed="right" min-width="150"
                         show-overflow-tooltip>
          <template #default="scope"> {{ scope.row.qualifiedMark || '--' }}</template>
        </el-table-column>
        <el-table-column prop="unQualifiedQuantity" align="center" label="不合格数量" fixed="right" min-width="100"
                         show-overflow-tooltip></el-table-column>
      </el-table>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="configTableShow = false">关闭</el-button>
          <!--          <el-button type="primary" @click="handleSaveConfig()">保存</el-button>-->
        </div>
      </template>
      <!-- 配置质检项 -->
      <el-dialog v-model="showConfig" title="配置质检项" width="1000">
        <el-form :model="configData" label-width="130px" class="demo-ruleForm">
          <el-row :gutter="10">
            <!-- 检验标准录入方式 -->
            <el-col :span="12">
              <el-form-item label="检验标准录入方式" prop="judgmentCriteria">
                <el-input v-model="configData.judgmentCriteria" placeholder="请输入检验标准录入方式"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 上公差 -->
            <el-col :span="12">
              <el-form-item label="上公差" prop="upperValue">
                <el-input v-model="configData.upperValue" placeholder="请输入上公差" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 默认值 -->
            <el-col :span="12">
              <el-form-item label="默认值" prop="defaultValue">
                <el-input v-model="configData.defaultValue" placeholder="请输入默认值" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 下公差 -->
            <el-col :span="12">
              <el-form-item label="下公差" prop="lowerValue">
                <el-input v-model="configData.lowerValue" placeholder="请输入下公差" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 不良判定方式 -->
            <el-col :span="12">
              <el-form-item label="不良判定方式" prop="defectMethod">
                <el-input v-model="configData.defectMethod" placeholder="请输入不良判定方式"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 标准值 -->
            <el-col :span="12">
              <el-form-item label="标准值" prop="otherDefect">
                <el-input v-model="configData.otherDefect" placeholder="请输入标准值" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 备注 -->
            <el-col :span="12">
              <el-form-item label="备注" prop="memo">
                <el-input v-model="configData.memo" placeholder="请输入备注" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 是否启用 -->
            <el-col :span="12">
              <el-form-item label="是否启用" prop="isEnable">
                <el-input v-model="configData.isEnable" placeholder="请输入是否启用" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 上警戒值 -->
            <el-col :span="12">
              <el-form-item label="上警戒值" prop="upperBias">
                <el-input v-model="configData.upperBias" placeholder="请输入上警戒值" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 下警戒值 -->
            <el-col :span="12">
              <el-form-item label="下警戒值" prop="lowerBias">
                <el-input v-model="configData.lowerBias" placeholder="请输入下警戒值" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- SPC坐标 -->
            <el-col :span="12">
              <el-form-item label="SPC坐标" prop="excelCoordinate">
                <el-input v-model="configData.excelCoordinate" placeholder="请输入SPC坐标"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <!-- 全尺寸坐标 -->
            <el-col :span="12">
              <el-form-item label="全尺寸坐标" prop="fullSizeCoordinate">
                <el-input v-model="configData.fullSizeCoordinate" placeholder="请输入全尺寸坐标"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="量具坐标" prop="toolCoordinate">
                <el-input v-model="configData.toolCoordinate" placeholder="请输入量具坐标"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="SPC检" prop="spcInspection">
                <el-input v-model="configData.spcInspection" placeholder="请输入全尺寸坐标"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="全尺寸检" prop="excelCoordinate">
                <el-input v-model="configData.fullSizeInspection" placeholder="请输入全尺寸检"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文件名称" prop="excelCoordinate">
                <el-input v-model="configData.failNameCode" placeholder="请输入文件名称"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数值类型" prop="excelCoordinate">
                <el-input v-model="configData.dataType" placeholder="请输入数值类型" style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检项代码" prop="testitemCode">
                <el-input v-model="configData.testitemCode" placeholder="请输入质检项名称"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检项名称" prop="excelCoordinate">
                <el-input v-model="configData.testitemName" placeholder="请输入质检项名称"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检类型" prop="excelCoordinate">
                <el-input v-model="configData.testitemclassificationName" placeholder="质检类型"
                          style="width: 300px"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <div class="dialog-footer">
            <el-button @click="showConfig = false">取消</el-button>
            <el-button type="primary" @click="handleSaveConfig">保存</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="showMaterial" title="添加可适用物料" width="500">
        <el-form :model="materialData" label-width="130px" class="demo-ruleForm">
          <el-row :gutter="10">
            <el-form-item label="选择物料">
              <el-select v-model="materialId" placeholder="请选择选择物料" clearable style="width: 300px">
                <el-option v-for="(item, index) of materialList" :key="index" :label="item.materialName"
                           :value="item.id">
                  <span style="float: left">{{ item.materialName }}</span>
                  <span style="
          float: right;
          color: var(--el-text-color-secondary);
          font-size: 13px;
        "> {{ item.materialNo }} </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <div class="dialog-footer">
            <el-button @click="showMaterial = false">取消</el-button>
            <el-button type="primary" @click="handleSaveMaterial">保存</el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import axiosInstance from '@/utils/http/api';
import {Edit, Refresh, Search} from '@element-plus/icons-vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import {computed, reactive, ref} from 'vue';
import axios from 'axios';
import moment from 'moment';

onMounted(() => {
  handleSearch();
  // getMaterial()
  getQualityPlanList();
});

const qualityPlanList = ref({});

const getQualityPlanList = () => {
  axiosInstance.post('/api/basedataQualityScheme/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        qualityPlanList.value = res.data;
        console.log(qualityPlanList.value);
      });
};


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const schemeTaskForm = ref({});

const configTableShow = ref(false);


const handleClick = (e) => {
  console.log(e, 'handleClick');
};
// 配置质检项表
const configTable = ref([]);

// 可适用物料
const materialTable = ref([]);


const rowInfo = ref({});
// 点击配置质检项表
const handleConfigEdit = (e) => {
  const row = {...e}
  console.log(row);
  rowInfo.value = row;
  // const list = JSON.parse(row.qualityJson);
  // schemeTaskForm.value = list.schemeTaskForm ? list.schemeTaskForm : [];
  schemeTaskForm.value = row.schemeTaskForm ? row.schemeTaskForm : [];
  // configTable.value = list.configTable;
  const param = JSON.parse(row.qualityJson);
  configTable.value = JSON.parse(row.qualityResultJson ?? row.qualityJson)?.configTable ?? [];
  const loop = {...param, ...row};
  Object.assign(formData, loop);
  isEdit.value = true;
  configTableShow.value = true;
};

const expandSearch = ref(false); // 控制检索条件的展开和收起

const tableHeight = computed(() => {
  return expandSearch.value ? 'calc(100vh - 520px)' : 'calc(100vh - 370px)';
});


const materialList = ref({});

const materialData = ref({});
const showMaterial = ref(false);
// 质检列表
const isConfigEdit = ref(false);

const isConfigIndex = ref(null);


const getQualityPlan = (e) => {
  let name = '';
  qualityPlanList.value.forEach(item => {
    if (item.id == e) {
      name = item.name;
    }
  });
  return name;
};

const getQualityWay = (e) => {
  let name = '';
  qualityWayList.value.forEach(item => {
    if (item.value == e) {
      name = item.label;
    }
  });
  return name;
};

const getQualityTypeList = (e) => {
  let name = '';
  qualityTypeList.value.forEach(item => {
    if (item.value == e) {
      name = item.label;
    }
  });
  return name;
};


// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
  axiosInstance.put('/api/basedataQualityScheme/update', updatedRowInfo).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
    // showConfig.value = false;
    // showMaterial.value = false
    configTableShow.value = false;
    // 刷新配置质检项列表
    // handleConfigEdit(rowInfo.value);
    handleSearch();
  });
};


const materialId = ref(null);
// 报错适配物料
const handleSaveMaterial = () => {
  const jsonParam = JSON.parse(rowInfo.value.qualityJson);
  for (const item of materialTable.value) {
    if (item.id == materialId.value) {
      ElMessage.error('该物料已存在');
      return false;
    }
  }
  let param = ref({});
  for (const items of materialList.value) {
    if (items.id == materialId.value) {
      param = items;
    }
  }
  // 保存
  // 存在则push
  if (jsonParam.materialTable && jsonParam.materialTable.length) {
    jsonParam.materialTable.unshift(param);
  } else {
    // 不存在则创建
    jsonParam.materialTable = [param];

  }

  rowInfo.value.qualityJson = JSON.stringify(jsonParam);
  handleUpdateQualityScheme(rowInfo.value);
};


// 质检项表删除 新建 编辑
const handleSaveConfig = () => {
  const jsonParam = JSON.parse(rowInfo.value.qualityJson);
  if (!schemeTaskForm.value.qualifiedQuantity) {
    ElMessage.error('请输入合格数量');
    return false;
  }
  if (!schemeTaskForm.value.unQualifiedQuantity) {
    ElMessage.error('请输入不合格数量');
    return false;
  }
  if (!schemeTaskForm.value.schemeTaskRemark) {
    ElMessage.error('请输入不良原因');
    return false;
  }
  jsonParam.schemeTaskForm = schemeTaskForm.value;
  jsonParam.configTable = configTable.value;
  rowInfo.value.status = true;
  delete jsonParam.qualityJson;
  rowInfo.value.qualityJson = JSON.stringify(jsonParam);
  handleUpdateQualityScheme(rowInfo.value);
};


const pageTotal = ref(null);//页面总数
// const formData = reactive({});//form表单
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const showConfig = ref(false);
const configData = ref({});
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});//弹出层标题

// 质检方式
const qualityWayList = ref([
  {
    label: '全检',
    value: '1'
  }, {
    label: '比例抽检',
    value: '2'
  }, {
    label: '固定抽检',
    value: '3'
  }, {
    label: '自定义抽检',
    value: '4'
  }
]);

const handleExport = (row) => {
  axios.post('/api/qualitySchemeTask/exportQualityResultExcel', {
    id: row.id
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', row.no + '质检项' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};


// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null;
  for (const item of qualityTypeList.value) {
    if (e == item.value) {
      name = item.label;
    }
  }
  return name;
};

// 质检类型
const qualityTypeList = ref([
  {
    label: '首件检',
    value: '1',
    type: 'material'
  },
  {
    label: '末件检',
    value: '2',
    type: 'material'
  },
  {
    label: '生产',
    value: '3',
    type: 'material'
  },
  {
    label: '巡检',
    value: '4',
    type: 'material'
  },
  {
    label: '入库检',
    value: '5',
    type: 'procedure'
  },
  {
    label: '出库检',
    value: '6',
    type: 'procedure'
  },
  {
    label: '来料检',
    value: '7',
    type: 'procedure'
  }
  // 继续添加更多检查类型...
]);

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  name: string;
  code: string;
  qualityWay: string;
  proportionNumber: string;
  qualityNumber: string;
  qualityType: string;
  qualityInterval: number;
  qualityIsLive: boolean;
  qualityRemark: string;
  qualityJson: string;
}


const originalFormData = reactive<RuleForm>({
  name: '',
  code: '',
  qualityWay: null,
  proportionNumber: 1,
  qualityNumber: 1,
  qualityType: '',
  qualityInterval: 1,
  qualityIsLive: true,
  qualityRemark: '',
  qualityJson: null
});

let formData = reactive<RuleForm>(originalFormData);


const rules = reactive<FormRules<formData>>({
  sourceNo: [
    {required: true, message: '请输入来源单号', trigger: 'blur'}
  ],
  qualityPlan: [
    {required: true, message: '请选择质检方案', trigger: 'blur'}
  ],
  samplingMethod: [
    {required: true, message: '请选择质检方式', trigger: 'blur'}
  ]
});


// const paginatedData = reactive([])//列表数据
const paginatedData = ref<RuleForm[]>([]);

// 获取列表接口
const handleSearch = () => {
  axiosInstance.post('/api/qualitySchemeTask/getPage', {
    ...searchParam.value,
    ...pageSearch.value,
    ...{
      status: true
    }
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }

        const loop = JSON.parse(JSON.stringify(res.data.records));
        const dataLoop = loop.map(item => {
          const list = JSON.parse(item.qualityJson);
          return {
            ...list,
            ...item,
            id: item.id,
            qualityPlanName: list.name
          };
        });

        paginatedData.value = dataLoop;
        console.log(paginatedData.value);

        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  handleSearch();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  handleSearch();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  handleSearch();
};

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  // ruleFormRef.value.resetFields()
  formData = reactive({});
  showCrud.value = true;
};

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  const param = JSON.parse(row.qualityJson);
  const list = {...param, ...row};
  Object.assign(formData, list);
  showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/qualitySchemeTask/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      handleSearch(); // 刷新数据
    });


  });
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      const jsonString = JSON.stringify(formData);
      formData.qualityJson = jsonString;
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/qualitySchemeTask/update', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          handleSearch(); // 刷新数据
        });
      } else {
        // 新建
        const paramData = formData;
        paramData.id = null;
        paramData.status = false;
        axiosInstance.post('/api/qualitySchemeTask/save', paramData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          handleSearch(); // 刷新数据
        });
      }

    }
  });
};
</script>
<style scoped>
.content {
  /*padding: 20px;*/
}
</style>
